import { fetchList,postUserMemberExpiration,transfer,postSalesman,deleteSalesman,getUserAddrsses,updateAddress,updateNote } from '@/api/user'
import { getSales,postUser } from '@/api/salesman'
import Pagination from '@/components/Pagination'
import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  name: 'User',
  components: { Pagination },
  data() {
    return {
      area_options: regionData,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: '',
        salesman: ''
      },
      sales_options:[
        {
          value: null,
          label: '不限'
        }
      ],
      salesman: null,
      expired_at: null,
      dialogVisible: false,
      memberVisible: false,
      addressVisible: false,
      from_salesman: null,
      to_salesman: null,
      addressFormData: {
        consignee: null,
        mobile: null,
        address: null,
        postal_code: null
      },
      rules: {
        mobile: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        consignee: [{
          required: true,
          message: '请输入联系人',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请输入详细地址',
          trigger: 'blur'
        }],
      },
      selected_area: null,

      noteVisible:false,
      noteForm:{
        note:null
      },
      user_id: null
    }
  },
  created() {
    this.getList()
    this.getSales()
  },
  methods: {
    preUpdateNote(data){
      this.noteVisible=true
      this.user_id = data.id
      this.noteForm = {
        note:data.note
      }
    },
    closeNoteForm(){
      this.noteVisible = false
    },
    preUpdateAddress(id){
      getUserAddrsses(id).then(res => {
        this.addressFormData = res.addresses[0]
        this.addressVisible = true
      }).catch(err => {
        this.$message({
          showClose: true,
          message: '找不到用户收货地址',
          type: 'warning'
        });
      })
    },
    updateNote(){
      if(this.noteForm.note && this.noteForm.note != ''){
        updateNote(this.user_id,{
          note:this.noteForm.note
        }).then(res => {
          this.noteVisible = false
          this.handleSearch()
        })
      }else{
        this.noteVisible = false
      }
    },
    updateAddress(){
      let data = this.addressFormData
      this.$refs['addressForm'].validate(valid => {
        if (!valid) return
        if(!data.district || !data.postal_code){
          this.$message.error('请选择地区');
          return
        }
        updateAddress(data.id,data).then(res => {
          this.addressVisible = false
          this.handleSearch();
        })
      })
    },
    onSelectedArea(v){
      let district = CodeToText[v[0]] + CodeToText[v[1]] + CodeToText[v[2]]
      this.addressFormData.district = district
      this.addressFormData.postal_code = v[2]
      this.selected_area = v
    },
    getSales: async function() {
      const options = this.sales_options
      const res = await getSales();
      for(const v of res.list){
        options.push({
          value:v.id,
          label:v.nickname
        })
      }
    },
    getList: function() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.users
        this.total = response.total
        this.listLoading = false
      }).catch(error => {
        this.list = []
        this.total = 0
        this.listLoading = false
        Promise.reject(error)
      })
    },
    handleSearch: function() {
      this.list = []
      this.listQuery.page = 1
      this.getList()
    },
    preTransfer(id){
      this.tid = id
      this.dialogVisible = true
    },
    preReset(id){
      this.tid = id
      this.memberVisible = true
    },
    handleTransfer: async function(){
      const id = this.tid
      const salesman = this.salesman
      const res = await postUser(id,{salesman: salesman})
      this.$notify({
        title: '成功',
        message: '转移成功',
        type: 'success',
        duration: 2000
      })
      this.dialogVisible = false
      this.handleSearch();
    },

    handleResetExpiredAt: async function(){
      const id = this.tid
      const expired_at = this.expired_at
      const res = await postUserMemberExpiration(id,{expired_at: expired_at})
      this.$notify({
        title: '成功',
        message: '操作成功',
        type: 'success',
        duration: 2000
      })
      this.memberVisible = false
      this.handleSearch();
    },

    transfer() {
      let fromeSalesman = this.from_salesman
      let toSalesman = this.to_salesman
      transfer({
        from_salesman: fromeSalesman,
        to_salesman: toSalesman
      }).then(res => {
        this.$notify({
          title: '成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.memberVisible = false
        this.handleSearch();
      })
    },

    addSalesman(id){
      console.log('postSalesman')
      postSalesman({user_id:id}).then(res=>{
        this.$message({
          message: '操作成功',
          type: 'success'
        });
        this.handleSearch()
      })
    },

    removeSalesman(id){
      deleteSalesman({user_id:id}).then(res=>{
        this.$message({
          message: '操作成功',
          type: 'success'
        });
        this.handleSearch()
      })
    }
  }
}
